//
//  GameLayer.m
//  newFinding
//
//  Created by Shin Stupid on 7/31/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#import "GameLayer.h"
#import "Little.h"

@implementation GameLayer

@synthesize labText = _labText;
@synthesize littleImage, lits;

static GameLayer *gamelayerInstance=nil;

#pragma mark Init
-(id) init
{
	if(self==[super init])
	{
       
        gamelayerInstance=self;
        //[self setIsTouchEnabled:TRUE];
        lits = [[NSMutableArray alloc] init];
        [self drawImg];
    }
    return self;
}
+(GameLayer*)getGameLayerInstance
{
    return gamelayerInstance;
}
#pragma mark -Delegate
-(void)touchRight:(id)sender:(CGPoint)point
{
    currentlittle=(Little *)sender ;
    po = point;
}
-(void)touchMove:(CGPoint)p
{
    if(currentlittle.img==nil){return;}
    //NSLog(@"Move tag Piece %d",currentlittle.img.tag);
    // get piece byTag demo moving peice
    CCSprite *peicce=currentlittle.img ;//
    CGFloat fMove = 0;
    int xLocation, yLocation;
    ShuffleMove move = [self validMove:currentlittle];
    if(move == UP && p.y > po.y)
    {
        fMove = (p.y - po.y)/50;
        xLocation = currentlittle.currentPosition.x;
        yLocation = currentlittle.currentPosition.y;
        CGFloat newY = peicce.position.y + fMove;
        if(newY >= (littleLevel-1-yLocation)*(tileHeight + 4) + tileHeight + 4 - tileHeight/2)
        {
            newY = (littleLevel-1-yLocation)*(tileHeight + 4) + tileHeight + 4;
            blankPosition = CGPointMake(blankPosition.x, blankPosition.y + 1);
            
            currentlittle.currentPosition = CGPointMake(xLocation, yLocation-1);
        }
        peicce.position = ccp(peicce.position.x, newY);
    }
    if(move == DOWN && po.y > p.y)
    {
        fMove = (po.y - p.y)/50;
        CGFloat newY = peicce.position.y - fMove;
        if(newY <= (littleLevel-1-currentlittle.currentPosition.y)*(tileHeight + 4) - (tileHeight + 4) + tileHeight/2)
        {
            newY = (littleLevel-1-currentlittle.currentPosition.y)*(tileHeight + 4) - (tileHeight + 4);
            currentlittle.currentPosition = blankPosition;
            blankPosition = CGPointMake(blankPosition.x, blankPosition.y - 1);
        }
       
        peicce.position = ccp(peicce.position.x, newY);
    }
    if(move == LEFT && po.x > p.x)
    {
        fMove = (po.x - p.x)/50;
        CGFloat newX = peicce.position.x - fMove;
        if(newX <= (currentlittle.currentPosition.x)*(tileWidth + 4) - (tileWidth + 4) + tileWidth/2)
        {
            newX = (currentlittle.currentPosition.x)*(tileWidth + 4) - (tileWidth + 4);
            currentlittle.currentPosition = blankPosition;
            blankPosition = CGPointMake(blankPosition.x + 1, blankPosition.y);
        }
        
        peicce.position = ccp(newX, peicce.position.y);
        
    }
    if(move == RIGHT && p.x > po.x)
    {
        fMove = (p.x - po.x)/50;
        CGFloat newX = peicce.position.x + fMove;
        if(newX >= (currentlittle.currentPosition.x)*(tileWidth + 4) + (tileWidth + 4) - tileWidth/2)
        {
            newX = (currentlittle.currentPosition.x)*(tileWidth + 4) + (tileWidth + 4);
            currentlittle.currentPosition = blankPosition;
            blankPosition = CGPointMake(blankPosition.x - 1, blankPosition.y);
        }
        
        peicce.position = ccp(newX, peicce.position.y);
    }
}

-(void)touchEnd:(CGPoint)p
{
    NSLog(@"Current Position Y: %f", currentlittle.currentPosition.y);
    int temp = currentlittle.img.position.y/(tileHeight + 4);
    if(currentlittle.img.position.y - temp*(tileHeight+4) != 0 || currentlittle.img.position.x - temp*(tileWidth+4) != 0)
        currentlittle.img.position = ccp(currentlittle.currentPosition.x * (tileWidth + 4), (littleLevel - 1 - currentlittle.currentPosition.y) *(tileHeight +4));
    if([self checkDone:lits] == YES)
    {
        UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"A" message:@"Finish" delegate:self cancelButtonTitle:nil otherButtonTitles:@"YES", nil] autorelease];
        [alert show];
        return;
    }
}

-(void)drawImg
{
    [self initPuzzle];
}

-(void)choosee:(id)sender
{
    //[self changePageWithScene:[MenuScene node] type:25];
}

-(void)initPuzzle
{
    littleLevel = 3;
    CCSprite *isLoad=[CCSprite spriteWithFile:@"1.png"];
    tileWidth = isLoad.textureRect.size.width/littleLevel;
    tileHeight = isLoad.textureRect.size.height/littleLevel;
    
    blankPosition = CGPointMake( 0, 0);
    
    [self.lits removeAllObjects];
    
    int tag=0;
    
    for(int i = 0; i < littleLevel; i++)
        for(int j = 0; j < littleLevel; j++)
        {
            CGPoint orgPosition = CGPointMake(i, j);
            
            CGRect frame = CGRectMake(tileWidth*i, tileHeight*j,
									  tileWidth, tileHeight );
			
            CCTexture2D* texture = [[CCTextureCache sharedTextureCache] addImage:@"1.png"];
            CCSpriteFrame* frameS = [CCSpriteFrame frameWithTexture:texture rect:frame];
            
            littleImage = [Little node];
            
             
            //[littleImage setAnchorPoint:ccp(0,0)];
            //littleImage.position=ccp(-175,0);
            CCSprite *sImg = [CCSprite spriteWithSpriteFrame:frameS];
            littleImage.img = sImg;
            [littleImage.img setAnchorPoint:ccp(0,0)];
			littleImage.img.position = ccp( (tileWidth+4)*i, (tileHeight+4)*(littleLevel-1-j));
			littleImage.originalPosition = orgPosition;
			littleImage.currentPosition = orgPosition;
            littleImage.delegate = self;
            /// quan ly cai little image bang tag
            littleImage.img.tag=TagPiece+tag;
            tag++;
            if(i !=0 || j != 0)
            {
                [lits addObject:littleImage];
                [self addChild:littleImage];
                [[Little getLittleInstance] addChild:littleImage.img];
            }
        }
    
    [self shuffle];
}

-(void) shuffle{
	NSMutableArray *validMoves = [[NSMutableArray alloc] init];
	
	srandom(time(NULL));
	
	for( int i=0; i<100; i++ )
    {
		[validMoves removeAllObjects];
		
		// get all of the pieces that can move
        //NSLog(@"litss count %d", [lits count]);
		for( Little *t in self.lits ){
			if( [self validMove:t] != NONE ){
				[validMoves addObject:t];
			}
		}
		
		// randomly select a piece to move
        int ran = validMoves.count;
		NSInteger pick = random()%ran;
		//NSLog(@"shuffleRandom using pick: %d from array of size %d", pick, [validMoves count]);
		[self movePiece:(Little *)[validMoves objectAtIndex:pick] withAnimation:NO];
	}
	
	[validMoves release];
}

-(void) movePiece:(Little *) tile withAnimation:(BOOL) animate{
    
    ShuffleMove temp= [self validMove:tile];
    
	switch ( temp ) {
		case UP:
			[self movePiece:tile
			   inDirectionX:0 inDirectionY:-1 withAnimation:animate];
			break;
		case DOWN:
			[self movePiece:tile
			   inDirectionX:0 inDirectionY:1 withAnimation:animate];
			break;
		case LEFT:
			[self movePiece:tile
			   inDirectionX:-1 inDirectionY:0 withAnimation:animate];
			break;
		case RIGHT:
			[self movePiece:tile
			   inDirectionX:1 inDirectionY:0 withAnimation:animate];
			break;
		default:
			break;
	}
}

-(ShuffleMove) validMove:(Little *) lit{
	// blank spot above current piece
	if( lit.currentPosition.x == blankPosition.x && lit.currentPosition.y == blankPosition.y+1 ){
		return UP;
	}
	
	// bank splot below current piece
	if( lit.currentPosition.x == blankPosition.x && lit.currentPosition.y == blankPosition.y-1 ){
		return DOWN;
	}
	
	// bank spot left of the current piece
	if( lit.currentPosition.x == blankPosition.x+1 && lit.currentPosition.y == blankPosition.y ){
		return LEFT;
	}
	
	// bank spot right of the current piece
	if( lit.currentPosition.x == blankPosition.x-1 && lit.currentPosition.y == blankPosition.y ){
		return RIGHT;
	}
	
	return NONE;
}

-(void) movePiece:(Little *) lit inDirectionX:(NSInteger) dx inDirectionY:(NSInteger) dy withAnimation:(BOOL) animate{
	lit.currentPosition = CGPointMake( lit.currentPosition.x+dx,
                                      lit.currentPosition.y+dy);
	blankPosition = CGPointMake( blankPosition.x-dx, blankPosition.y-dy );
	
	int x = lit.currentPosition.x;
	int y = lit.currentPosition.y;
	
	if( animate ){
		[UIView beginAnimations:@"frame" context:nil];
	}
    //UIImage *orgImage = [UIImage imageNamed:@"1.jpeg"];
	lit.img.position = CGPointMake((tileWidth+4)*x, (tileHeight+4)*(littleLevel-1-y));
	if( animate ){
		[UIView commitAnimations];
	}
}

-   (BOOL)checkDone:(NSMutableArray *) array
{
    for(Little *lit in array)
    {
        if(lit.currentPosition.x != lit.originalPosition.x || lit.currentPosition.y != lit.originalPosition.y)
            return NO;
    }
    return YES;
}

-(void)dealloc
{
    [littleImage release];
    [lits release];
    [super dealloc];
}

@end
